/*
 * Created by JFormDesigner on Wed Feb 22 17:29:52 CST 2017
 */

package com.chq.version;

import com.chq.version.log.LogChangedEvent;
import com.chq.version.log.LogChangedListener;
import com.chq.version.log.LogMonitor;
import com.chq.version.util.FileUtil;
import com.chq.version.util.PropertiesUtil;
import com.chq.version.util.SVNUtil;
import com.chq.version.util.ZipUtil;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.io.SVNRepository;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Properties;

/**
 * @author c
 */
public class IndexFrame {
    public IndexFrame() {
        initComponents();
        init();
    }

    private void init() {
        //加载配置文件
        Properties ps=PropertiesUtil.getProperties("conn");
        textFieldSVNdz.setText(ps.getProperty("svn.url"));
        textFieldSVNUsername.setText(ps.getProperty("svn.username"));
        passwordFieldSVNPasswrod.setText(ps.getProperty("svn.password"));
        textFieldSVNStartRevision.setText(ps.getProperty("svn.revision"));
        textFieldVersionPath.setText(ps.getProperty("path.version"));

        // 日志信息变更监听处理（关键点）
        LogMonitor.addLogChangedListener(new LogChangedListener() {
            @Override
            public void eventActivated(LogChangedEvent me) {
                textAreaLog.setText(LogMonitor.getLogs().toString());
                textAreaLog.setCaretPosition(textAreaLog.getText().length());
                textAreaLog.paintImmediately(textAreaLog.getBounds());
            }
        });
        LogMonitor.addLog("更新日志：");
    }

    private void button1MouseClicked(MouseEvent e) {
        //获取版本号
        long revision = Long.parseLong(textFieldSVNStartRevision.getText());
        //项目路径
        String itemsPath = textFieldVersionPath.getText() + "\\items";
        //临时存储路径
        String tempPath = textFieldVersionPath.getText() + "\\temp";
        //压缩包打包路径
        String zipPath = textFieldVersionPath.getText() + "\\zip";
        String svnUrl = textFieldSVNdz.getText();
        String svnUsername = textFieldSVNUsername.getText();
        String svnPassword = String.valueOf(passwordFieldSVNPasswrod.getPassword());
        File itemsPathFile = new File(itemsPath + "\\.svn");
        if (itemsPathFile.exists()) {
            //文件夹已经存在
            LogMonitor.addLog("开始更新项目！");
            SVNUtil.doUpdate(itemsPath, svnUsername, svnPassword);
        } else {
            //文件夹不存在，检出项目
            LogMonitor.addLog("开始检出项目！");
            SVNUtil.checkOut(svnUrl, svnUsername, svnPassword, itemsPath);
        }
        //连接SVN
        SVNRepository repository = SVNUtil.getSVNRepository(svnUrl, svnUsername, svnPassword);
        //SVN最后版本
        long latestRevision = -1;
        try {
            latestRevision = SVNUtil.getLatestRevision(repository);
        } catch (SVNException svne) {
            svne.printStackTrace();
        }
        try {
            FileUtil.delFilePath(tempPath);
            LogMonitor.addLog("开始拷贝项目文件！");
            SVNUtil.copyCodeToDestPath(repository, revision, tempPath, itemsPath);
            //删除历史文件
            FileUtil.delFilePath(zipPath + "es_v1.0.0." + revision + "_" + latestRevision + ".zip");
            //生成压缩包
            LogMonitor.addLog("开始压缩更新包！");
            ZipUtil.zip(tempPath, zipPath, "es_v1.0.0." + revision + "_" + latestRevision + ".zip");
            LogMonitor.addLog("打包完成！" + "es_v1.0.0." + revision + "_" + latestRevision + ".zip");
            Runtime.getRuntime().exec("cmd /c start " + zipPath);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        indexFrame = new JFrame();
        panel1 = new JPanel();
        label1 = new JLabel();
        textFieldSVNdz = new JTextField();
        label2 = new JLabel();
        textFieldSVNUsername = new JTextField();
        label3 = new JLabel();
        passwordFieldSVNPasswrod = new JPasswordField();
        label4 = new JLabel();
        textFieldSVNStartRevision = new JTextField();
        label5 = new JLabel();
        textFieldVersionPath = new JTextField();
        button1 = new JButton();
        scrollPane1 = new JScrollPane();
        textAreaLog = new JTextArea();

        //======== indexFrame ========
        {
            indexFrame.setVisible(true);
            indexFrame.setTitle("SVN\u9879\u76ee\u6253\u5305\u5de5\u5177");
            indexFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            indexFrame.setResizable(false);
            Container indexFrameContentPane = indexFrame.getContentPane();
            indexFrameContentPane.setLayout(new BorderLayout());

            //======== panel1 ========
            {
                panel1.setLayout(null);

                //---- label1 ----
                label1.setText("SVN\u5730\u5740\uff1a");
                panel1.add(label1);
                label1.setBounds(6, 40, 98, label1.getPreferredSize().height);
                panel1.add(textFieldSVNdz);
                textFieldSVNdz.setBounds(110, 35, 315, textFieldSVNdz.getPreferredSize().height);

                //---- label2 ----
                label2.setText("SVN\u767b\u5f55\u540d\uff1a");
                panel1.add(label2);
                label2.setBounds(6, 77, 98, 17);
                panel1.add(textFieldSVNUsername);
                textFieldSVNUsername.setBounds(110, 70, 315, 25);

                //---- label3 ----
                label3.setText("SVN\u5bc6\u7801\uff1a");
                panel1.add(label3);
                label3.setBounds(6, 114, 98, 17);
                panel1.add(passwordFieldSVNPasswrod);
                passwordFieldSVNPasswrod.setBounds(110, 110, 315, passwordFieldSVNPasswrod.getPreferredSize().height);

                //---- label4 ----
                label4.setText("\u68c0\u51fa\u8d77\u59cb\u7248\u672c\uff1a");
                panel1.add(label4);
                label4.setBounds(6, 151, 98, 17);
                panel1.add(textFieldSVNStartRevision);
                textFieldSVNStartRevision.setBounds(110, 150, 315, 25);

                //---- label5 ----
                label5.setText("\u66f4\u65b0\u5305\u8def\u5f84\uff1a");
                panel1.add(label5);
                label5.setBounds(6, 188, 98, label5.getPreferredSize().height);
                panel1.add(textFieldVersionPath);
                textFieldVersionPath.setBounds(110, 185, 315, 25);

                //---- button1 ----
                button1.setText("\u751f\u6210\u66f4\u65b0\u5305");
                button1.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        button1MouseClicked(e);
                    }
                });
                panel1.add(button1);
                button1.setBounds(275, 220, 150, button1.getPreferredSize().height);

                //======== scrollPane1 ========
                {
                    //---- textAreaLog ----
                    textAreaLog.setText("\u66f4\u65b0\u65e5\u5fd7\uff1a");
                    scrollPane1.setViewportView(textAreaLog);
                }
                panel1.add(scrollPane1);
                scrollPane1.setBounds(10, 255, 420, 195);

                { // compute preferred size
                    Dimension preferredSize = new Dimension();
                    for(int i = 0; i < panel1.getComponentCount(); i++) {
                        Rectangle bounds = panel1.getComponent(i).getBounds();
                        preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                        preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                    }
                    Insets insets = panel1.getInsets();
                    preferredSize.width += insets.right;
                    preferredSize.height += insets.bottom;
                    panel1.setMinimumSize(preferredSize);
                    panel1.setPreferredSize(preferredSize);
                }
            }
            indexFrameContentPane.add(panel1, BorderLayout.CENTER);
            indexFrame.setSize(460, 500);
            indexFrame.setLocationRelativeTo(indexFrame.getOwner());
        }
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JFrame indexFrame;
    private JPanel panel1;
    private JLabel label1;
    private JTextField textFieldSVNdz;
    private JLabel label2;
    private JTextField textFieldSVNUsername;
    private JLabel label3;
    private JPasswordField passwordFieldSVNPasswrod;
    private JLabel label4;
    private JTextField textFieldSVNStartRevision;
    private JLabel label5;
    private JTextField textFieldVersionPath;
    private JButton button1;
    private JScrollPane scrollPane1;
    private JTextArea textAreaLog;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}
